package java_thinking.unit_19._19_10;


import java.util.EnumMap;

/**
 * @Desc:   用 EnumMap 进行邮件分发
 * @author: cww
 * @DateTime: 2019/5/24 9:42
 */

interface Command { boolean handle(Mail m); }

public class E09_PostOffice2 {
    static EnumMap<PostOffice.MailHandler,Command> em =
            new EnumMap<PostOffice.MailHandler, Command>(PostOffice.MailHandler.class);
    static {
        em.put(PostOffice.MailHandler.GENERAL_DELIVERY, new Command() {
            @Override
            public boolean handle(Mail m) {
                switch (m.generalDelivery) {
                    case YES:
                        System.out.println("Using general delivery for " + m);
                        return true;
                    default:
                    return false;
                }
            }
        });
        em.put(PostOffice.MailHandler.MACHINE_SCAN, new Command() {
            @Override
            public boolean handle(Mail m) {
                switch (m.scannability) {
                    case UNSCANNABLE: return false;
                    default:
                        switch (m.address) {
                            case INCORRECT: return false;
                            default:
                                System.out.println("Delivering "+ m + " automatically");
                                return true;
                        }
                }
            }
        });
        em.put(PostOffice.MailHandler.VISUAL_INSPECTION, new Command() {
            public boolean handle(Mail m) {
                switch(m.readability) {
                    case ILLEGIBLE: return false;
                    default:
                        switch(m.address) {
                            case INCORRECT: return false;
                            default:
                                System.out.println("Delivering " + m + " normally");
                                return true;
                        }
                }
            }
        });
        em.put(PostOffice.MailHandler.RETURN_TO_SENDER, new Command() {
            public boolean handle(Mail m) {
                switch(m.returnAddress) {
                    case MISSING: return false;
                    default:
                        System.out.println("Returning " + m + " to sender");
                        return true;
                }
            }
        });
    }
    enum MailHandler {
        GENERAL_DELIVERY, MACHINE_SCAN, VISUAL_INSPECTION, RETURN_TO_SENDER;
    }
    static void handle(Mail m) {
        for(Command cmd : em.values())
            if(cmd.handle(m))
                return;
        System.out.println(m + " is a dead letter");
    }
    public static void main(String[] args) {
        for(Mail mail : Mail.generator(10)) {
            System.out.println(mail.details());
            handle(mail);
            System.out.println("*****");
        }
    }
}
